﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;

namespace FSY.API.Utilities
{
    public class Fsy_ImageUtil
    {
        /// <summary>
        /// Saves the resized image to specified file name and path as JPEG
        /// and also returns the bytearray for any other use you may need it for
        /// </summary>
        /// <param name="MaxSideSize"></param>
        /// <param name="Buffer">fileUpload.PostedFile.InputStream</param>
        /// <param name="fileName">No Extension</param>
        /// <param name="filePath">Examples: "images/dir1/dir2" or "images" or "images/dir1"</param>
        /// <returns></returns>
        public static byte[] SaveResizeImageFromStream(Stream Buffer, string fileName, string filePath,int newWidth,int newHeight)
        {
            byte[] byteArray = null;  // really make this an error gif 
            try
            {                            
                Image oImg = Image.FromStream(Buffer);
                Image oThumbNail = new Bitmap(newWidth, newHeight);

                Graphics oGraphic = Graphics.FromImage(oThumbNail);
                oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle oRectangle = new Rectangle
                    (0, 0, newWidth, newHeight);

                oGraphic.DrawImage(oImg, oRectangle);

                //Save File
                string newFileName = string.Format(System.Web.HttpContext.Current.Server.MapPath("~/{0}/{1}.jpg"), filePath, fileName);
                oThumbNail.Save(newFileName, ImageFormat.Jpeg);

                MemoryStream ms = new MemoryStream();
                oThumbNail.Save(ms, ImageFormat.Jpeg);
                byteArray = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(byteArray, 0, Convert.ToInt32(ms.Length));

                oGraphic.Dispose();
                oImg.Dispose();
                ms.Close();
                ms.Dispose();
            }
            catch
            {
            }
            return byteArray;
        }
    }
}
